package com.qys.livesMall.shop.service.impl;

import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.dto.FinancePayDTO;
import com.qys.livesMall.finance.service.FinanceBusinessService;
import com.qys.livesMall.shop.constants.OrderStatus;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuStocksMapper;
import com.qys.livesMall.shop.modal.entity.ShopOrderInfo;
import com.qys.livesMall.shop.modal.entity.ShopOrderSku;
import com.qys.livesMall.shop.service.ShopAutoShippedService;
import com.qys.livesMall.shop.service.ShopOrderInfoService;
import com.qys.livesMall.shop.service.ShopOrderSkuService;
import com.qys.livesMall.shop.service.ShopOrderStatusManager;
import com.qys.livesMall.shop.task.ShopTaskInter;
import com.qys.livesMall.system.service.IH2SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @menu ShopAutoShippedServiceImpl
 * @date 2023/10/23 15:11
 */
@Slf4j
@Service
public class ShopAutoShippedServiceImpl implements ShopAutoShippedService {

    @Autowired
    private IH2SysConfigService sysConfigService;

    @Autowired
    private ShopOrderInfoService shopOrderInfoService;

    @Autowired
    private ShopOrderSkuService shopOrderSkuService;

    @Autowired
    private ShopGoodsSkuStocksMapper skuStocksMapper;

    @Autowired
    private FinanceBusinessService financeBusinessService;

    @Autowired
    private ShopOrderStatusManager shopOrderStatusManager;

    @Autowired
    private ShopTaskInter shopTaskInter;

    @Override
    public void createTask() {
        log.info("自动发货开始....");
        int outTime=1;
        String time=sysConfigService.getConfigKey("shipped_out_time");
        if (Strings.isBlank(time)){
            outTime=48;
        }else {
            outTime=Integer.parseInt(time);
        }
        long start=System.currentTimeMillis()-outTime*3600*1000;
        long end =start+3600*1000;
        List<ShopOrderInfo> outOrders = shopOrderInfoService.getOutTimeShipped(0, end);
        if (CollectionUtils.isEmpty(outOrders)){
            log.info("自动发货结束,共发货0单");
            return;
        }
        for(ShopOrderInfo order:outOrders){

            //触发时间
            Long eventLong=(order.getPayTime()+outTime*3600*1000+5000-System.currentTimeMillis())/1000;
            if (eventLong<=0){
                eventLong=(long)(Math.random()*3600);
            }
            int eventTime =Integer.valueOf(eventLong.toString());
            shopTaskInter.shippedTask(eventTime,order.getId());
        }
    }

    public void exc(Long orderId){
        ShopOrderInfo order = shopOrderInfoService.getById(orderId);
        if (order == null) {
            return;
        }
        List<ShopOrderSku> orderSkus=shopOrderSkuService.getByOrderId(orderId);
        for(ShopOrderSku orderSku:orderSkus){
            if (!Objects.equals(orderSku.getOrderStatus(), OrderStatus.UNSHIPPED)){
                continue;
            }
            if (Objects.equals(orderSku.getCostPay(), Constants.YesNoInt.NO)){
                //退款
                orderSku.setOrderStatus(OrderStatus.RETURNED);
                orderSku.setReturnBeforeStatus(OrderStatus.UNSHIPPED);
                orderSku.setEndTime(System.currentTimeMillis());
                shopOrderSkuService.updateById(orderSku);

                //退款
                //判断是否退运费
                BigDecimal postage=new BigDecimal("0");

                //未发货，可能退运费
                List<ShopOrderSku> categorySkus = orderSkus.stream()
                        .filter(o -> Objects.equals(o.getShopId(), orderSku.getShopId()))
                        .filter(o -> Objects.equals(o.getCategoryId(), orderSku.getCategoryId()))
                        .filter(o -> !Objects.equals(o.getId(),orderSku.getId()))
                        .collect(Collectors.toList());
                if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(categorySkus)){
                    postage=orderSku.getPostage();
                }else {
                    for (ShopOrderSku temp:categorySkus){
                        if (Objects.equals(temp.getOrderStatus(),OrderStatus.UNSHIPPED)
                                ||Objects.equals(temp.getOrderStatus(),OrderStatus.SHIPPED)
                                ||Objects.equals(temp.getOrderStatus(),OrderStatus.RECEIVED)
                                ||Objects.equals(temp.getOrderStatus(),OrderStatus.RETURN_APPLIED)
                                ||Objects.equals(temp.getOrderStatus(),OrderStatus.RETURN_CONFIRMED)
                        ){
                            postage = BigDecimal.ZERO;
                            break;
                        }
                        if (Objects.equals(temp.getOrderStatus(),OrderStatus.RETURNED)){
                            if (Objects.equals(temp.getReturnBeforeStatus(),OrderStatus.UNSHIPPED)){
                                postage=orderSku.getPostage();
                            }
                        }
                    }
                }
                BigDecimal moneys = orderSku.getMoney().add(postage);
                FinancePayDTO financePayDTO = new FinancePayDTO();
                financePayDTO.setUserId(Long.valueOf(orderSku.getUserId()));
                financePayDTO.setAmountIncurred(moneys);
                financePayDTO.setBusinessType(AccountBusinessTypeEnum.USER_ORDER_RETURN_AFTER);
                financePayDTO.setBusinessNo(orderSku.getSkuOrderId());
                if(orderSku.getSettlementStatus().equals("0")){
                    Integer num = orderSku.getNum();
                    int stocksCount = skuStocksMapper.decount(orderSku.getStocksId(), -num);
                    if(stocksCount<1){
                        throw new QysException(MessageUtils.message("system.error.order"));
                    }
                    financePayDTO.setBusinessType(AccountBusinessTypeEnum.USER_ORDER_RETURN_BEFORE);
                }
                financeBusinessService.pay(financePayDTO);
                if(!financePayDTO.getSuccess()){
                    throw new QysException(financePayDTO.getMessage());
                }
            }else {
                //发货
                orderSku.setOrderStatus(OrderStatus.SHIPPED);
                orderSku.setConsignTime(System.currentTimeMillis());
                shopOrderSkuService.updateById(orderSku);
            }
        }
        //同步状态
        order.setOrderStatus(shopOrderStatusManager.getMainOrderStatus(orderSkus));
        shopOrderInfoService.updateById(order);
    }
}

